<?php
session_start();

//accessing the members registration file
$file = 'members.txt';

if(file_exists($file))
{
    //reading the file into an array
    $users = file($file);
    $valid = false;

    if (isset ($_POST['submit']) && $_POST['username'] != '')
    {
        //assigning the entered value to a variable
        $username = $_POST['username'];
        $pword = $_POST['pword'];

        //looping through the file searching for names
        for ($i = 0; $i < count($users); $i++)
        {
            //extract each element use comma space fo deliminator and trim any white space around elements
            $temp = explode(', ', trim($users[$i]));

            //creating the new array
            $users[$i] = array('username' => $temp[0], 'pword' => rtrim($temp[1]));

            //here we check if the submitted name is in the registered members file
            if ($users[$i]['username'] == $username && $users[$i]['pword'] == $pword)
            {
                //if there is a match set valid user to true and break out of the loop
                $_SESSION['username'] = $username;


                //user validated
                $valid = true;
                break;
            }
            else if ($username == "" || $pword == "")
            {
                $_SESSION['message'] = "<p><span style='color: red; font-weight: bold;'>Please check your details. If you have not registered, please register here</span></p>";
                $valid = false;
            }
            else
            {
                $_SESSION['message'] = "<p><span style='color: red; font-weight: bold;'>Please check your details. If you have not registered, please register here</span></p>";
                $valid = false;
            }
        }
    }
}
else
{
      $_SESSION['message'] = "<p><span style='color: red; font-weight: bold;'>File Does not Exist. Please Register.</span></p>";
}

if($valid = true)
{
	$_SESSION['messageWelcome'] = "<p><span style='color: green; font-weight: bold;'>Welcome</span></p>";
        header("Location: main.php");        
}
else if(!$valid)
{
	$_SESSION['message'] = "<p><span style='color: red; font-weight: bold;'>You are not a valid user. Please Register.</span></p>";
	header("Location: Register.php");
        $_SESSION = array();
}
?>
